package com.ykw.parking.controller;

import com.ykw.parking.Utils.GetUUID;
import com.ykw.parking.mapper.UserMapper;
import com.ykw.parking.pojo1.LoanBean;
import com.ykw.parking.pojo1.User;
import com.ykw.parking.pojo1.UserLoan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.awt.image.DataBuffer;
import java.sql.Date;
import java.util.List;

@Controller
public class LoanController {

    @Autowired
    UserMapper userMapper;
    @RequestMapping("/loan")
    public  String getLoanPage(){
        return "loan";
    }

    @RequestMapping("/myloan")
    public  String getMyloanPage(){
        return "myloan";
    }

    @RequestMapping(value = "/addLoan",method = RequestMethod.POST)
    @ResponseBody
    public String addLoan(String name, String address, String contact, String company, Double money, HttpSession session){
        String  username = (String)session.getAttribute("username");
        User user = userMapper.queryUserbyname(username);
        System.out.println(new Date(System.currentTimeMillis()));
        UserLoan userLoan = new UserLoan(GetUUID.getUUID(), name, address, contact, company, money,0.0, new Date(System.currentTimeMillis()),user.getId());
        int i = userMapper.addLoan(userLoan);
        if (i>0){
            double money1 = userMapper.getMoney(user.getId());
            userMapper.addMoney(money+money1,user.getId());
            return "贷款成功";
        }else{
            return "贷款失败";
        }
    }

    @RequestMapping(value = "/getMyLoan",method = RequestMethod.POST)
    @ResponseBody
    public List<UserLoan> getMyLoan(HttpSession session){
        String  username = (String)session.getAttribute("username");
        User user = userMapper.queryUserbyname(username);
        List<UserLoan> myLoan = userMapper.getMyLoan(user.getId());
        return myLoan;
    }

    @RequestMapping(value = "/repayment",method = RequestMethod.POST)
    @ResponseBody
    public String repayment(String id,Double money,HttpSession session){
        String  username = (String)session.getAttribute("username");
        User user = userMapper.queryUserbyname(username);
        double money1 = userMapper.getMoney(user.getId());
        if(money1-money<0){
            return "金额不够，还款失败";
        }
        userMapper.addMoney(money1-money,user.getId());
        UserLoan myLoanMoney = userMapper.getMyLoanMoney(id);
        if(money<=myLoanMoney.getInterest()){
            userMapper.updLoan(myLoanMoney.getInterest()-money,id);
        }else{
            userMapper.updLoanBean((myLoanMoney.getInterest()+myLoanMoney.getMoney())-money,id);
        }
        return "还款成功";
    }
}
